//
//  BTPublicHelper.swift
//  XiaoweHearingAid
//
//  Created by Riven on 2023/3/7.
//

import Foundation
import AVFAudio


/// 获取音频蓝牙连接的外设
func getBluetoothA2DPOutputDevice() -> AVAudioSessionPortDescription? {
    let route = AVAudioSession.sharedInstance().currentRoute
    for iOutput in route.outputs {
        let portType = iOutput.portType
        log.info("AVAudioSession.output = \(iOutput)")
        
        if portType == AVAudioSession.Port.bluetoothA2DP || portType == AVAudioSession.Port.bluetoothHFP {
            return iOutput
        }
    }
    
    return nil
}

func getBluetoothA2DPDeviceName() -> String? {
    guard let outputDevice = getBluetoothA2DPOutputDevice() else {
        log.error("未连接音频蓝牙")
        return nil
    }
    
    return outputDevice.portName
}

/// 获取音频蓝牙连接的 UUID
func getBluetoothA2DPUUID() -> String? {
    guard let outputDevice = getBluetoothA2DPOutputDevice() else {
        log.error("未连接音频蓝牙")
        return nil
    }
    let uuid = outputDevice.uid
    return uuid
}

func getBluetoothA2DPMacAddress() -> String? {
    guard let a2dpUUID = getBluetoothA2DPUUID() else {
        log.error("未连接音频蓝牙")
        
        return nil
    }
    guard let a2dpMac = parseBluetoothA2DPAddress(a2dpUUID: a2dpUUID) else {
        log.error("音频蓝牙地址解析错误, a2dpUUID = \(a2dpUUID) \n")
        return nil
    }
    
    return a2dpMac
}

func getBluetoothA2DPOutputs() -> [AVAudioSessionPortDescription] {
    var retOutputs: [AVAudioSessionPortDescription] = []
    
    let route = AVAudioSession.sharedInstance().currentRoute
    log.info("AVAudioSession.outputs = \(route.outputs)")

    for iOutput in route.outputs {
        let portType = iOutput.portType
        if portType == AVAudioSession.Port.bluetoothA2DP || portType == AVAudioSession.Port.bluetoothHFP {
            retOutputs.append(iOutput)
        }
    }
    
    return retOutputs
}

func parseBluetoothA2DPAddress(a2dpUUID: String?) -> String? {
    guard let a2dpUUID = a2dpUUID else { return nil }
    
    if a2dpUUID.count <= 17 {
        return nil
    }
    
    return String(a2dpUUID.prefix(17))
}
